<template>
  <div>
    <a-button type="primary" @click="showModal">新增用户</a-button>
    <a-modal v-model:open="open" title="新增用户" @ok="handleOk">
      <EditForm ref="rForm"></EditForm>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, defineEmits, nextTick } from 'vue'
import EditForm from './edit-form.vue'
import { userRegisterApi } from '@/api/auth.api.ts'
import { localhostUpload } from '@/api/upload.api.ts'
import type { CreateUserDto } from '@/api/user.api.ts'

const emits = defineEmits(['editOk'])

const open = ref<boolean>(false)

const showModal = () => {
  open.value = true
  nextTick(() => {
    rForm.value?.clearFormState()
  })
}

const rForm = ref()
const handleOk = () => {
  rForm.value.submit().then(async (res: CreateUserDto) => {
    if (res.avatarFile) {
      const formData = new FormData()
      formData.append('file', res.avatarFile)
      const { fileUrl } = await localhostUpload(formData)
      res.avatar = fileUrl
    }
    delete res.avatarFile
    await userRegisterApi(res)
    open.value = false
    emits('editOk')
  })
}

defineOptions({
  name: 'AddDictModal',
})
</script>
